package biz

import (
	"context"
	remote "manage/api/user"
	"strings"
	"time"

	"github.com/Fromsko/gouitls/auth"
	"github.com/Fromsko/gouitls/logs"
	"github.com/go-kratos/kratos/v2/log"
)

var echo = logs.InitLogger()

func NewUserCase(repo UserRepo, logger log.Logger) *UserCase {
	return &UserCase{
		repo:       repo,
		log:        log.NewHelper(logger),
		subscriber: &auth.SubscriberAuth{},
	}
}

// CreateUser 创建用户
func (receiver *UserCase) CreateUser(ctx context.Context, user *remote.AddUserRequest) (*remote.UserResponse, error) {
	currentTime := time.Now()

	u, err := receiver.repo.Create(ctx, &UserInfo{
		UserID:    strings.Split(auth.GenUUID(user.Username), "-")[0],
		Username:  user.Username,
		Password:  auth.HashString(user.Password),
		Email:     user.Email,
		Role:      user.Role,
		CreatedAt: currentTime,
		UpdatedAt: currentTime,
	})

	if err != nil {

		echo.Warnf("[%s] %s", user.Username, err)

		return &remote.UserResponse{
			Code: 400,
			Msg:  "创建失败:用户已存在",
			Data: nil,
		}, nil
	}

	return &remote.UserResponse{
		Code: 200,
		Msg:  "创建成功",
		Data: &remote.User{UserId: u.UserID},
	}, nil
}

// DeleteUser 实现删除用户逻辑
func (receiver *UserCase) DeleteUser(ctx context.Context, userID *remote.DeleteUserRequest) (*remote.UserResponse, error) {
	reply := &remote.UserResponse{
		Code: 200,
		Msg:  "删除成功",
		Data: nil,
	}

	if err := receiver.repo.Delete(ctx, userID.UserId); err != nil {
		reply.Msg = err.Error()
	}

	return reply, nil
}

// UpdateUser 实现更新用户逻辑
func (receiver *UserCase) UpdateUser(ctx context.Context, req *remote.UpdateUserRequest) (*remote.UserResponse, error) {
	userInfo := &UserInfo{
		UserID:    req.UserId,
		Username:  req.Username,
		Password:  auth.HashString(req.Password),
		Role:      req.Role,
		Email:     req.Email,
		UpdatedAt: time.Now(),
	}

	user, err := receiver.repo.Update(ctx, userInfo)
	if err != nil {
		if err.Error() == "用户不存在" {
			return &remote.UserResponse{
				Code: 400,
				Msg:  "更新失败:用户不存在",
				Data: nil,
			}, nil
		}
		return &remote.UserResponse{
			Code: 400,
			Msg:  "更新失败:用户名唯一",
			Data: nil,
		}, nil
	}

	return &remote.UserResponse{
		Code: 200,
		Msg:  "更新成功",
		Data: &remote.User{
			UserId:   user.UserID,
			Username: user.Username,
			Email:    user.Email,
		},
	}, nil
}

// GetUser 实现查询用户逻辑
func (receiver *UserCase) GetUser(ctx context.Context, req *remote.GetUserRequest) (*remote.UserResponse, error) {
	user, err := receiver.repo.Query(ctx, req.UserId)
	if err != nil {
		return &remote.UserResponse{
			Code: 400,
			Msg:  "查询失败:用户不存在",
			Data: nil,
		}, nil
	}

	return &remote.UserResponse{
		Code: 200,
		Msg:  "查询成功",
		Data: &remote.User{
			UserId:   user.UserID,
			Username: user.Username,
			Password: user.Password,
			Email:    user.Email,
			Role:     user.Role,
		},
	}, nil
}

// GetUserList 实现查询用户列表逻辑
func (receiver *UserCase) GetUserList(ctx context.Context, req *remote.GetUserListRequest) (*remote.GetUserListReply, error) {
	// 按照角色获取
	role := req.Role
	reply := &remote.GetUserListReply{Code: 200, Msg: "查询成功"}

	userList, _ := receiver.repo.QueryList(ctx, role)
	if len(userList) == 0 {
		reply.Code = 400
		reply.Msg = "角色不存在"
	} else {
		replyList := []*remote.User{}
		for _, info := range userList {
			user := &remote.User{
				UserId:   info.UserID,
				Username: info.Username,
				Password: info.Password,
				Email:    info.Email,
				Role:     info.Role,
			}
			replyList = append(replyList, user)
		}
		reply.UserList = replyList
	}

	return reply, nil
}
